package com.example.demo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class PrintSequentially {

    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition1 = lock.newCondition();
    private static final Condition condition2 = lock.newCondition();
    private static final Condition condition3 = lock.newCondition();
    private static int state = 1; // 代表当前要打印的数字

    public static void main(String[] args) {
        Thread t1 = new Thread(PrintSequentially::print1);
        Thread t2 = new Thread(PrintSequentially::print2);
        Thread t3 = new Thread(PrintSequentially::print3);

        t1.start();
        t2.start();
        t3.start();

        // 等待所有线程自然完成
    }

    private static void print1() {
        while (true) {
            lock.lock();
            try {
                while (state != 1) {
                    condition1.await();
                }
                System.out.println("1");
                state = 2;
                condition2.signal();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } finally {
                lock.unlock();
            }
        }
    }

    private static void print2() {
        while (true) {
            lock.lock();
            try {
                while (state != 2) {
                    condition2.await();
                }
                System.out.println("2");
                state = 3;
                condition3.signal();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } finally {
                lock.unlock();
            }
        }
    }

    private static void print3() {
        while (true) {
            lock.lock();
            try {
                while (state != 3) {
                    condition3.await();
                }
                System.out.println("3");
                state = 1;
                condition1.signal();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            } finally {
                lock.unlock();
            }
        }
    }
}
